define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    require('../../../xsyBase');

    var approvalService = require('oldcrm/js/apps/approval/approvalService')

    $.widget('rk.xsyApprovalBar', $.rk.xsyBase, {
        _create : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;


            elem.addClass('xsy_approval_bar')
            elem.hide();

            me._loadData({}, function (result){
                opt.data = result;
                opt.data.common.entityType = result.self.entityTypeId;
                me.taskid = result.self.taskid ? result.self.taskid : '';
                me.showApprovalBar();
            });

            me._listenOuterEvent('submitApproval', function(info){
                if($.isFunction(info.callback)){
                    info.callback(me.taskid);
                }
            });
        },

        _init : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;
            /*opt.data = '{"canSubmit":0,"isParallelGateway":"1","isCounterSigner":"0","canSubmitApproval":false,"showApprovalStatus":true,"canApproveApproval":"","submitBtnName":"提交","approvalStatus":1,"currentApproval":"59662","currentApprovalList":[],"opinion":"","belongId":1,"entityTypeId":88636,"createdBy":59662,"objectName":"B3","objectId":229909,"canModify":false,"canCheck":0,"returnTypeList":[],"relationBelongs":[{"id":"343905","name":"????","item":"603394","count":"0","entityTypes":[{"id":"300293","typeName":"????????????"}]},{"id":"343906","name":"????","item":"604816","count":"0","entityTypes":[{"id":"300294","typeName":"????"}]},{"id":"344201","name":"????","item":"604820","count":"0","entityTypes":[{"id":"300489","typeName":"????????????"}]},{"id":"345110","name":"????","item":"605463","count":"0","entityTypes":[{"id":"301299","typeName":"????????????"}]},{"id":"345115","name":"??????????","item":"605490","count":"0","entityTypes":[{"id":"301307","typeName":"????????????"},{"id":"301309","typeName":"??????1"}]},{"id":"345116","name":"????????","item":"605544","count":"0","entityTypes":[{"id":"301308","typeName":"????????????"}]}],"account":{"id":"229909","accountName":"B3","state":"","location":"","longitude":"","latitude":"","address":"","phone":"","url":"","expireTime":"","groupId":"203054","ownerId":"59662","highSeaStatus":"4","canApplyDelay":"0","summary":""},"object":{"createdBy":"59662","createdAt":"11??13?? 11:49","approvalTime":"1??????","hasApprovers":"false","approversLength":"0","allowSelectApprover":"false","defaultApprover":"","approvers":[],"applyId":"229909","taskid":"56669a4645cef93135c033b5"},"processList":{"approvals":[{"result":3,"approvalUserId":59662,"approvalTime":"53??????","operateType":1,"opinion":"","signApprovals":[]},{"result":5,"approvalUserId":63201,"approvalTime":"53??????","operateType":5,"opinion":"","signApprovals":[]},{"result":3,"approvalUserId":59662,"approvalTime":"1??????","operateType":3,"opinion":"","signApprovals":[]},{"result":-1,"approvalUserId":59662,"approvalTime":"1??????","operateType":"","opinion":"","signApprovals":[]}],"flowSteps":[]},"members":[],"ownerMembers":[],"documents":[{"id":"50006","filename":"????.png","filetype":"file_class_document"},{"id":"50005","filename":"????2.jpg","filetype":"file_class_document"}],"permission":{"license":{"hs":"1"},"func":{"343905":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"343906":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344201":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344301":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344302":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344501":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344502":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345110":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345114":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345115":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345116":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345117":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345118":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345126":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345606":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"cas":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1},"expenseaccount":{"v":1,"d":1,"u":1,"e":1,"s":1,"c":1,"l":1,"m":0},"lead":{"v":1,"d":1,"u":1,"e":1,"t":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"contact":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"order":{"v":1,"d":1,"u":1,"e":1,"s":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"terminal":{"v":0,"d":0,"u":0,"e":0,"tr":0,"c":0,"mg":0,"l":0,"m":0,"i":0},"partner":{"v":1,"d":1,"u":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"campaign":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1},"contract":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1},"approval":{"m":1},"visitcollect":{"l":0},"agent":{"v":0,"d":0,"u":0,"e":0,"tr":0,"c":0,"mg":0,"l":0,"m":0,"i":0},"product":{"cp":0,"op":0,"l":1,"m":1},"opportunity":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"mg":1,"l":1,"m":1,"i":1},"expense":{"v":1,"d":1,"u":1,"e":1,"c":1,"l":1,"m":1},"salesgoal":{"d":1,"u":1,"c":1,"l":1,"m":1,"i":1},"account":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"mg":1,"l":1,"m":1,"i":1},"competitor":{"v":1,"d":1,"u":1,"tr":1,"c":1,"l":1,"m":1},"isSuperHSAdmin":"0"},"data":{"update":0,"transfer":0,"del":0,"view":1}},"users":{"59662":{"id":"59662","name":"??","icon":"https://devrs.s3.cn-north-1.amazonaws.com.cn/36705/2015/10/14/s_ff8b1852-5f2b-4694-a57e-83e0bdee4cc8.png"},"63201":{"id":"63201","name":"yangxh","icon":"https://devrs.s3.cn-north-1.amazonaws.com.cn/36705/2015/12/02/s_7ed33188-dc1e-49f3-945d-06f09364f4e8.jpg"}},"relation":{"flag":"true","type":"f","status":"false"},"currencyUnit":"","highSea":{"id":"62102","name":"????????","recycleRule":"0","transferRule":"0","highSeaType":"","isHighSeaAdmin":"0","highSeaRules":"????????10??????????????????????????&lt;br&gt;????????20??????????????????????????&lt;br&gt;"},"highsealogs":[],"opportunityTypeList":[{"id":"88637","typeName":"????????????"},{"id":"89336","typeName":"????"},{"id":"89337","typeName":"????2"}],"orderTypeList":[{"id":"88641","typeName":"??????"},{"id":"89338","typeName":"????1"}],"tabNumbers":{"caseNum":"1","contactNum":"5","taskNum":"9","fileNum":"2","oppNum":"1","contractNum":"2","orderNum":"1","campaignNum":""},"itemAuth":{"entityType":1,"ownerId":1,"accountName":0,"dbcDate1":0,"level":0,"parentAccountId":0,"industryId":0,"state":0,"region":0,"longitude":0,"address":0,"latitude":0,"zipCode":0,"phone":0,"fax":0,"city":0,"url":0,"weibo":0,"employeeNumber":0,"annualRevenue":0,"recentActivityRecordTime":1,"recentActivityCreatedBy":1,"createdAt":1,"highSeaId":1,"createdBy":0,"highSeaAccountSource":0,"updatedAt":1,"claimTime":1,"updatedBy":0,"expireTime":1,"approvalStatus":0,"comment":0,"highSeaStatus":1,"dbcRelation1":0,"dbcRelation3":0,"applicantId":0,"dbcDate2":0,"dbcVarchar1":0,"dbcVarchar2":0,"dbcRelation5":0,"dimDepart":0},"func":{"343905":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"343906":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344201":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344301":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344302":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344501":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"344502":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345110":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345114":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345115":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345116":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345117":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345118":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345126":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"345606":{"v":1,"d":1,"u":1,"t":1,"e":1,"c":1,"l":1,"m":1,"i":1},"cas":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1},"expenseaccount":{"v":1,"d":1,"u":1,"e":1,"s":1,"c":1,"l":1,"m":0},"lead":{"v":1,"d":1,"u":1,"e":1,"t":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"contact":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"order":{"v":1,"d":1,"u":1,"e":1,"s":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"terminal":{"v":0,"d":0,"u":0,"e":0,"tr":0,"c":0,"mg":0,"l":0,"m":0,"i":0},"partner":{"v":1,"d":1,"u":1,"tr":1,"c":1,"l":1,"m":1,"i":1},"campaign":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1},"contract":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"l":1,"m":1},"approval":{"m":1},"visitcollect":{"l":0},"agent":{"v":0,"d":0,"u":0,"e":0,"tr":0,"c":0,"mg":0,"l":0,"m":0,"i":0},"product":{"cp":0,"op":0,"l":1,"m":1},"opportunity":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"mg":1,"l":1,"m":1,"i":1},"expense":{"v":1,"d":1,"u":1,"e":1,"c":1,"l":1,"m":1},"salesgoal":{"d":1,"u":1,"c":1,"l":1,"m":1,"i":1},"account":{"v":1,"d":1,"u":1,"e":1,"tr":1,"c":1,"mg":1,"l":1,"m":1,"i":1},"competitor":{"v":1,"d":1,"u":1,"tr":1,"c":1,"l":1,"m":1},"isSuperHSAdmin":"0"},"oaMenuItems":[{"name":"schedule"},{"name":"task"},{"name":"rescenter"},{"name":"approval"},{"name":"workreport"},{"name":"colleague"},{"name":"group"},{"name":"privateMessage"}],"hasCrmAccess":true,"privateMsgUnRead":0,"tenantType":"0","financeStartMonth":"1","logoUrl":"","navValue":"","currentTime":"1449561495378","currentVersion":"3.6","DEFAULTS":{"USER_DEFAULT_ICON":"/static/img/default_face.png","TENANT_DEFULT_ICON":"/static/img/v3.0/logo.png","TENANT_CUSTOM_ICON":""},"currentUserId":"59662"}';
            me.showApprovalBar();*/
        },

        bindEventHandler : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var data = opt.data;


            /*elem.off('mouseover', '.xsy_approval_bar_check').on('mouseover', '.xsy_approval_bar_check', function() {
                elem.find('div.xsy_approval_wrap').show();
                elem.find('div.xsy_approval_wrap').find('.xsy_approval_process_list').beScroll();
            });
            elem.off('mouseout', '.xsy_approval_bar_check').on('mouseout', '.xsy_approval_bar_check', function() {
                elem.find('div.xsy_approval_wrap').hide();
            });*/

            var flowButton = elem.find('div.xsy_approval_bar_flow');
            var menu = elem.find('div.xsy_approval_wrap');
            flowButton.rkEasyMenu({
                menu:menu,
                openBy:'mouseover'
            })


            elem.off('click', '.xsy_approval_bar_agree').on('click', '.xsy_approval_bar_agree', function(){
                elem.find("div.js_approval_tip").show();
            });

            elem.off('click', '.xsy_approval_bar_reject').on('click', '.xsy_approval_bar_reject', function(){
                elem.find("div.js_reject_tip").show();
            })

            $('body').on('click.xsy_approval_bar_operate', function(e){
                if($(e.target).closest('.xsy_approval_bar_agree').size() > 0)return;
                if($(e.target).closest('.xsy_approval_bar_tip').size() > 0) return;
                if($(e.target).closest('.ui-autocomplete').size() > 0) return;
                elem.find('.js_approval_tip').hide();
            })

            $('body').on('click.xsy_approval_bar_operate', function(e){
                if($(e.target).closest('.xsy_approval_bar_reject').size() > 0)return;
                if($(e.target).closest('.xsy_approval_bar_tip').size() > 0) return;
                if($(e.target).closest('.ui-autocomplete').size() > 0) return;
                elem.find('.js_reject_tip').hide();
            })

            elem.off('click', '.xsy_approval_bar_people_select').on('click', '.xsy_approval_bar_people_select', function(){
                var $this = $(this);
                var userSelectSpan = $this.find("span");
                var container = $this.parent();
                var approvalBarSelectMenu = $('div.xsy_approval_bar_selectmenu');
                var approvalUserSelect = container.find("#xsy_approval_user_select");
                var approvalUser_hidden = container.find(":hidden.approvalUser_hidden");


                approvalUserSelect.rkUser({
                    onSelect : function(userId, userName){
                        userSelectSpan.text(userName);
                        approvalBarSelectMenu.hide();
                        approvalUser_hidden.val(userId);
                    }
                });

                if (!approvalBarSelectMenu.is(":hidden")) {
                    approvalBarSelectMenu.hide();
                } else {
                    approvalBarSelectMenu.show();
                }
            })

            elem.on('click', 'li.xsy_approval_bar_selectmenu_itme', function(e){
                var $this = $(this);
                var name = $this.find("a").text();
                var id = $this.find("a").attr("id");

                var userSelectSpan = elem.find('span.xsy_approval_bar_people_select span');
                var approvalUser_hidden = elem.find(':hidden.approvalUser_hidden');
                var approvalBarSelectMenu = elem.find('div.xsy_approval_bar_selectmenu');

                approvalBarSelectMenu.hide();
                userSelectSpan.text(name);
                approvalUser_hidden.val(id);

            });

            elem.off('click', '.js_submit').on('click', '.js_submit', function(e){
                var $this = $(this);
                var result = $this.attr("value");
                var formObj = $this.parents("form");
                var approvalUserHidden = formObj.find(":hidden.approvalUser_hidden")[0];
                var taEle = formObj.find("[name='commentContent']");

                if($.trim(taEle.val()).length > 800){
                    $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_1'));
                    return false;
                }

                if(result == 0){
                    if ($.trim(taEle.val()) == "") {
                        $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_2'));
                        return false;
                    }
                } else if(result == 1){
                    /*if((data.self.hasApprovers == true || data.self.allowSelectApprover == true || data.self.isParallelGateway == 1) && approvalUserHidden && approvalUserHidden.value == ''){
                        $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_3'));
                        return false;
                    }*/

                    if(data.self.isParallelGateway != '1') {
                        if (approvalUserHidden) {
                            if (approvalUserHidden.value == "") {
                                $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_3'));
                                return false;
                            }
                        } else if (data.self.hasApprovers == true) {
                            $.msg('请选择下一步审批人');
                            return false;
                        }
                    }
                }

                if(data.self.isCounterSigner == '1'){
                    var confirmMsg = (result == 1 ? rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_1') : rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_3'));
                } else{
                    var confirmMsg = (result == 1 ? rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_1') : rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_2'));
                }

                rk.confirm(confirmMsg, function(){
                    var options = {
                        iframe: false,
                        resetForm : true,
                        beforeSubmit : function(){},
                        success : function(responseText){
                            var status = responseText.status;
                            var statusText = responseText.statusText;
                            if(status == 213003){
                                $.msg("当前的审批流程无法分配下一步审批人，审批流程无法继续执行，请通知提交人重新填写审批信息后，重新提交");
                                return false;
                            } else if(status == 310105){
                                //圣奥家居：客户提交、同意时，如果存在已报备的名称完全相同的客户，不允许新建
                                $.msg("已有重名客户通过报备");
                                return false;
                            } else if(status == 0){
                                $.msg("操作成功",1);
                                setTimeout(function(){window.location.reload();}, 1000);
                                
                            }
                        }
                    }
                    formObj.ajaxSubmit(options);
                });
            })

            //提交审批
            elem.off('click', '.xsy_approval_bar_submit').on('click', '.xsy_approval_bar_submit', function(e){
                var elementId = 'container';
                var $this = $('#' + elementId);
                $this.data = {};
                $this.data.belongId = data.common.belongId;
                $this.data.objectId = data.common.id;
                $this.data.objectName = data.common.name;
                $this.data.entityTypeId = data.common.entityType;
                $this.data.object = {};
                //提交报备的时候，taskid是不用传滴
                $this.data.object.taskid = me.taskid;

                //$this.data.object.taskid = taskid;
                approvalService.submitApproval(elementId, $this, {}, callback);

                function callback() {
                    me.refresh(window.location.href, '操作成功', 1);
                }
            })

            //撤回审批
            elem.off('click', '.xsy_approval_bar_recall').on('click', '.xsy_approval_bar_recall', function(e){
                var elementId = 'container';
                var $this = $('#' + elementId);
                $this.data = {};
                $this.data.belongId = data.common.belongId;
                $this.data.objectId = data.common.id;
                $this.data.objectName = data.common.name;
                $this.data.entityTypeId = data.common.entityType;
                $this.data.object = {};
                $this.data.object.taskid = me.taskid;
                approvalService.cancelApproval(elementId, $this, {}, callback);

                function callback() {
                    me.refresh(window.location.href, '操作成功', 1);
                }
            })

            //解除审批
            elem.off('click', '.xsy_approval_bar_relieve').on('click', '.xsy_approval_bar_relieve', function(e){
                var elementId = 'container';
                var $this = $('#' + elementId);
                $this.data = {};
                $this.data.belongId = data.common.belongId;
                $this.data.objectId = data.common.id;
                $this.data.objectName = data.common.name;
                $this.data.entityTypeId = data.common.entityType;
                $this.data.object = {};
                $this.data.object.taskid = me.taskid;
                approvalService.relieveApproval(elementId, $this, {}, callback);

                function callback() {
                    me.refresh(window.location.href, '操作成功', 1);
                }
            })
        },
        

        showApprovalBar : function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var data = opt.data.self;

            if(data.approvalStatus != undefined && data.showApprovalStatus){
                var tpl = require('platform/widgets/crm/approval/xsyApprovalBar/widget.tpl');
                elem.html(rk.templateText(tpl,data));
                elem.show();
                if(opt.data.self.hasWorkflow){
                    elem.after('<div class="xsy_approval_bar_hasborder"></div>');
                }

                me.bindEventHandler();
            }else{
                elem.hide();
            }
        },

        refresh : function (url, message, status) {
            setTimeout(function () {
                window.location.href = url
            }, 1000);
            if (message) {
                $.msg(message, status);
            }
        }
    });
});
